package cn.ydxiaoshuai.common.system.controller;


import cn.ydxiaoshuai.common.api.vo.oss.TencentPutObjectResult;
import cn.ydxiaoshuai.common.system.base.controller.ApiRestController;
import cn.ydxiaoshuai.common.system.vo.DelOssResponseBean;
import cn.ydxiaoshuai.common.system.vo.UploadOssResponseBean;
import cn.ydxiaoshuai.common.util.oConvertUtils;
import com.alibaba.fastjson.JSON;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xavier
 * @Description 腾讯云OSS
 * @Date  2020/5/14 14:20
 **/
@Controller
@RequestMapping("/rest/oss/tx")
public class TencentOssRestController extends ApiRestController {
    /**
     * 腾讯OSS应用参数KEY
     **/
    @Value(value = "${oss.tencent.accessKey}")
    private String accessKey;
    /**
     * 腾讯OSS应用参数SECRET
     **/
    @Value(value = "${oss.tencent.secretKey}")
    private String secretKey;
    /**
     * 腾讯OSS应用参数bucket的区域
     **/
    @Value(value = "${oss.tencent.bucket}")
    private String bucket;
    /**
     * 腾讯OSS应用参数存储桶名称
     **/
    @Value(value = "${oss.tencent.bucketName}")
    private String bucketName;
    /**
     * 腾讯OSS 图片URL前缀
     **/
    private String OSS_URL = "https://xai-1251091977.cos.ap-chengdu.myqcloud.com/";
    /**
     * @author xavier
     * @Description 保存图片到腾讯云OSS
     * @Date  2020/5/14 14:24
     * @param path 存放路径
     * @param file 多媒体文件
     * @return ResponseEntity
     **/
    @RequestMapping(value = "/upload/{path}", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseEntity<Object> uploadTencentOss(@PathVariable String path, @RequestParam(value = "file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        UploadOssResponseBean bean = new UploadOssResponseBean();
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
        // 2 设置bucket的区域 自己的哦
        ClientConfig clientConfig = new ClientConfig(new Region(bucket));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        //图片名称
        String key = file.getOriginalFilename();
        //后缀名
        String prefix = key.substring(key.lastIndexOf("."));
        //新的图片名称
        String newKey = System.currentTimeMillis()+prefix;

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path+"/"+newKey, file.getInputStream(), metadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        TencentPutObjectResult tencentPutObjectResult = JSON.parseObject(JSON.toJSONString(putObjectResult), TencentPutObjectResult.class);
        tencentPutObjectResult.setImg_url(OSS_URL+path+"/"+newKey);
        tencentPutObjectResult.setImg_name(newKey);
        bean.success("success", "上传成功", tencentPutObjectResult);
        //耗时
        timeConsuming = String.valueOf(System.currentTimeMillis()-startTime);
        //响应的内容
        beanStr = JSON.toJSONString(bean);
        cosClient.shutdown();
        return new ResponseEntity<Object>(beanStr, httpHeaders, HttpStatus.OK);
    }

    /**
     * @author xavier
     * @Description 删除图片腾讯云OSS
     * @Date  2020年9月4日14:57:46
     * @return ResponseEntity
     **/
    @RequestMapping(value = "/del/{path}", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseEntity<Object> delTencentOss(@PathVariable String path,HttpServletRequest request, HttpServletResponse response) throws Exception {
        DelOssResponseBean bean = new DelOssResponseBean();
        String key = ServletRequestUtils.getStringParameter(request, "key","");
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
        // 2 设置bucket的区域 自己的哦
        ClientConfig clientConfig = new ClientConfig(new Region(bucket));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        if(oConvertUtils.isEmpty(path)||oConvertUtils.isEmpty(key)){
            bean.fail("not enough param","参数缺失，请检查",410101);
        } else {
           cosClient.deleteObject(bucketName, path+"/"+key);
           bean.success("success", "操作成功");
        }
        //耗时
        timeConsuming = String.valueOf(System.currentTimeMillis()-startTime);
        //响应的内容
        beanStr = JSON.toJSONString(bean);
        cosClient.shutdown();
        return new ResponseEntity<Object>(beanStr, httpHeaders, HttpStatus.OK);
    }
}
